<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { ref, reactive, onMounted, watch, h } from 'vue'
import {
  ElCard,
  ElRow,
  ElCol,
  ElTable,
  ElTableColumn,
  ElButton,
  ElRadio,
  ElRadioGroup,
  ElInput,
  ElMessage,
  ElDialog,
  ElDivider,
  ElTag
} from 'element-plus'
import { Icon } from '@/components/Icon'
import { DifyRequest, DifyConfig } from '@/api/dify'
import request from '@/axios'
import { IntelligentChat, ChatSidebarPanel } from '@/components/IntelligentChat'
import { DIFY_API_V1_URL, DIFY_API_KEY_changjing2 } from '@/constants/dify'
import { Table, TableColumn } from '@/components/Table'
import { Search } from '@/components/Search'
import { useRouter } from 'vue-router'
import { getWorkOrderVerification } from '@/api/electricityAbnormal'
import { ecCategOptions } from '@/dicts'
import { getAbnormalOrderStatsZg } from '@/api/electricityAbnormal'

interface ChatSidebarInstance extends ComponentPublicInstance {
  openDrawer: () => void
  closeDrawer: () => void
}

const { t } = useI18n()

interface IResponse<T> {
  code: number
  data: T
  message: string
}

interface VerificationRecord {
  id: string
  workOrderNo: string
  verificationResult: string
  verificationTime: string
  verifier: string
  [key: string]: any
}

// 工单信息
const workOrderInfo = reactive({
  workOrderNo: '3225051610000258',
  businessType: '更名',
  demandType: '更名',
  processChannel: '网上自助',
  appointmentTime: '2025-05-07'
})

// 客户信息
const customerInfo = reactive({
  customerNo: '1200032507720',
  customerName: '林晓0328',
  newCustomerName: '林晓0336',
  remark: ''
})

// 审核/审批记录
const verificationRecords = reactive([
  {
    serialNo: 1,
    stage: '信息归档',
    result: '不通过',
    opinion: '没有按照相关规定办理',
    department: '河西大户管理区域',
    approver: '刘文杰',
    approvalTime: '2025-05-08 12:30:01'
  },
  {
    serialNo: 2,
    stage: '合同审批',
    result: '通过',
    opinion: '无',
    department: '河西大户管理区域',
    approver: '梁壮',
    approvalTime: '2025-05-08 10:50:55'
  },
  {
    serialNo: 3,
    stage: '合同审核',
    result: '通过',
    opinion: '通过',
    department: '河西大户管理区域',
    approver: '李冲',
    approvalTime: '2025-08-08 9:25:30'
  }
])

// 当前审核结果
const verificationResult = ref('不通过')
// 审核意见
const verificationOpinion = ref('')

// 提交审核
const submitVerification = () => {
  if (verificationResult.value === '不通过' && !verificationOpinion.value) {
    ElMessage.warning('请填写审核意见')
    return
  }

  ElMessage.success('审核提交成功')
}

// 档案核查弹窗相关
const fileVerificationDialogVisible = ref(false)
const isLoading = ref(false)
const verificationSuggestion = ref('')
const aiAnalysisError = ref('')

// 配置API请求
const config: DifyConfig = {
  apiKey: DIFY_API_KEY_changjing2,
  apiBase: DIFY_API_V1_URL
}

// 查看文件/档案核查
const viewFile = () => {
  fileVerificationDialogVisible.value = true
  startFileVerification()
}

// 开始档案核查
const startFileVerification = () => {
  isLoading.value = true
  verificationSuggestion.value = ''
  aiAnalysisError.value = ''

  // 准备传递给AI助手的结构化数据
  const structuredData = {
    workOrderNo: workOrderInfo.workOrderNo,
    businessType: workOrderInfo.businessType,
    demandType: workOrderInfo.demandType,
    processChannel: workOrderInfo.processChannel,
    appointmentTime: workOrderInfo.appointmentTime,
    customerNo: customerInfo.customerNo,
    customerName: customerInfo.customerName,
    newCustomerName: customerInfo.newCustomerName,
    remark: customerInfo.remark,
    verificationRecords: verificationRecords
  }

  // 准备发送给Dify的请求数据
  const difyRequest = {
    inputs: {
      workOrder: JSON.stringify(structuredData)
    },
    query: `请对这个工单进行档案核查，分析是否存在问题，并给出具体的核查整改建议。
工单信息: ${JSON.stringify(structuredData, null, 2)}`,
    response_mode: 'blocking',
    user: 'app-20250517'
  }

  console.log('开始档案核查，数据:', structuredData)

  // 使用request直接发送请求
  request
    .post<IResponse<any>>({
      url: `${config.apiBase}/chat-messages`,
      data: difyRequest,
      headers: {
        Authorization: `Bearer ${config.apiKey}`,
        'Content-Type': 'application/json'
      }
    })
    .then((res) => {
      const answer = res.answer || ''

      if (answer) {
        console.log('AI分析完成:', answer)
        // 尝试从回答中提取整改建议
        try {
          //提取出JSON数据
          const result = extractContentAndJson(answer)
          console.log('result', result)
          verificationSuggestion.value = processApiResponse(result.jsonData)
          aiAnalysisError.value = result.jsonData.error || ''
        } catch (error) {
          console.error('提取建议失败:', error)
          verificationSuggestion.value = '无法解析AI返回的建议'
        }
      } else {
        // 获取备用建议
        console.log('未获取到AI响应，使用备用分析结果')
        verificationSuggestion.value = '请求超时，已使用备用分析结果'
      }
    })
    .catch((error) => {
      console.error('AI分析失败:', error)
      aiAnalysisError.value = `分析出错: ${error?.message || '未知错误'}`
      // 使用备用方案
      verificationSuggestion.value = 'AI分析失败'
    })
    .finally(() => {
      isLoading.value = false
    })

  // 设置超时保护
  setTimeout(() => {
    if (isLoading.value) {
      isLoading.value = false
      verificationSuggestion.value = '请求超时，请重新提交'
      console.log('请求超时，已使用备用分析结果')
    }
  }, 100000) // 100秒超时
}
// 处理提取的JSON数据
const extractContentAndJson = (text: string) => {
  const result = {
    content: text,
    jsonData: null as any
  }

  // 移除<think>标签内容
  result.content = text.replace(/<think>([\s\S]*?)<\/think>/g, '')

  // 尝试提取JSON格式内容
  const jsonRegex = /```json\s*([\s\S]*?)\s*```/g
  const jsonMatches = [...result.content.matchAll(jsonRegex)]

  if (jsonMatches.length == 1) {
    try {
      const jsonText = jsonMatches[0][1].trim()
      result.jsonData = JSON.parse(jsonText)
    } catch (e) {
      console.error('JSON解析失败:', e)
    }
  }

  return result
}

// 处理API响应数据
const processApiResponse = (data) => {
  try {
    // 格式化分析结果和整改建议为易读的文本
    let formattedText = ''

    // 添加分析结果部分
    if (data['分析结果'] && Array.isArray(data['分析结果'])) {
      formattedText += '【分析结果】\n'
      data['分析结果'].forEach((item) => {
        const key = Object.keys(item)[0]
        formattedText += `${key}：${item[key]}\n`
      })
    }

    // 添加整改建议部分
    if (data['整改建议'] && Array.isArray(data['整改建议'])) {
      formattedText += '\n【整改建议】\n'
      data['整改建议'].forEach((item) => {
        const key = Object.keys(item)[0]
        formattedText += `${key}：${item[key]}\n`
      })
    }

    return formattedText
  } catch (error) {
    handleError(error)
    return '解析失败'
  }
}

// 处理错误
const handleError = (error) => {
  console.error('解析建议失败:', error)
  aiAnalysisError.value = `解析结果失败: ${error?.message || '未知错误'}`
  isLoading.value = false
}
// 关闭档案核查弹窗
const closeVerificationDialog = () => {
  fileVerificationDialogVisible.value = false
  verificationSuggestion.value = ''
  aiAnalysisError.value = ''
}

// 应用整改建议
const applyVerificationSuggestion = () => {
  if (verificationSuggestion.value) {
    verificationOpinion.value = verificationSuggestion.value
    closeVerificationDialog()
    ElMessage.success('已应用整改建议')
  }
}
// 表格样式，奇行背景色#f6f6f6偶行背景色#ffffff
const tableRowStyle = ({ rowIndex }: { rowIndex: number }) => {
  return rowIndex % 2 === 0 ? { background: '#ffffff' } : { background: '#fcfcfc' }
}

const handleSubmit = async () => {
  try {
    const res = (await updateWorkOrderVerification(submissionData)) as IResponse<any>
    if (res && res.code === 200) {
      ElMessage.success('提交成功')
      // ... existing code ...
    }
  } catch (error) {
    // ... existing code ...
  }
}

// 假设 submissionData 是表单数据，需定义
const submissionData = reactive<any>({})

// AI聊天相关
const chatSidebarRef = ref<ChatSidebarInstance | null>(null)
const aiInputs = ref({})
// 添加AI分析结果状态
const aiAnalysisResult = ref<any>(null)
// 添加details内容状态
const detailsContent = ref<any>(null)
// 处理AI会话完成
const handleAiFinish = (result: any) => {
  console.log('AI会话结束:', result)
  if (result.extractedJson) {
    // 保存提取的JSON数据
    aiAnalysisResult.value = result.extractedJson
    console.log('量费核算分析结果:', aiAnalysisResult.value)

    ElMessage.success('已提取分析结果')
  }

  // 处理details内容
  if (result.detailsContent) {
    detailsContent.value = result.detailsContent
    console.log('提取的details内容:', detailsContent.value)
    // 根据提取的数据进行相应处理
    // submitAnalysisToBackend()
  }
}
// 处理AI会话开始前
const handleBeforeOpen = () => {
  // 准备传递给AI助手的结构化数据
  const structuredData = {
    workOrderNo: workOrderInfo.workOrderNo,
    businessType: workOrderInfo.businessType,
    demandType: workOrderInfo.demandType,
    processChannel: workOrderInfo.processChannel,
    appointmentTime: workOrderInfo.appointmentTime,
    customerNo: customerInfo.customerNo,
    customerName: customerInfo.customerName,
    newCustomerName: customerInfo.newCustomerName,
    remark: customerInfo.remark,
    verificationRecords: verificationRecords
  }
  chatSidebarRef.value?.openDrawer()

  // 设置AI输入数据
  aiInputs.value = {
    workOrder: JSON.stringify(structuredData)
  }

  return true
}
</script>

<template>
  <div class="verification-page">
    <!-- 标题 -->
    <h2 class="page-title">用电信息申请</h2>

    <!-- 工单信息 -->
    <div class="info-section">
      <ElRow :gutter="20">
        <ElCol :span="6">
          <div class="info-item">
            <span class="label">工单编号：</span>
            <span class="value">{{ workOrderInfo.workOrderNo }}</span>
          </div>
        </ElCol>
        <ElCol :span="6">
          <div class="info-item">
            <span class="label">业务类型：</span>
            <span class="value">{{ workOrderInfo.businessType }}</span>
          </div>
        </ElCol>
        <ElCol :span="6">
          <div class="info-item">
            <span class="label">需求类型：</span>
            <span class="value">{{ workOrderInfo.demandType }}</span>
          </div>
        </ElCol>
        <ElCol :span="6">
          <div class="info-item">
            <span class="label">受理渠道：</span>
            <span class="value">{{ workOrderInfo.processChannel }}</span>
          </div>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20" class="mt-10">
        <ElCol :span="6">
          <div class="info-item">
            <span class="label">客户编号：</span>
            <span class="value">{{ customerInfo.customerNo }}</span>
          </div>
        </ElCol>
        <ElCol :span="6">
          <div class="info-item">
            <span class="label">客户名称：</span>
            <span class="value">{{ customerInfo.customerName }}</span>
          </div>
        </ElCol>
        <ElCol :span="6">
          <div class="info-item">
            <span class="label">新客户名称：</span>
            <span class="value">{{ customerInfo.newCustomerName }}</span>
          </div>
        </ElCol>
        <ElCol :span="6">
          <div class="info-item">
            <span class="label">预申请时间：</span>
            <span class="value">{{ workOrderInfo.appointmentTime }}</span>
          </div>
        </ElCol>
      </ElRow>

      <ElRow :gutter="20" class="mt-10">
        <ElCol :span="24">
          <div class="info-item">
            <span class="label">申请备注：</span>
            <span class="value">{{ customerInfo.remark }}</span>
          </div>
        </ElCol>
      </ElRow>
    </div>

    <!-- 审核/审批记录 -->
    <div class="verification-section mt-20">
      <h3 class="section-title page-title">审核/审批记录</h3>

      <ElTable
        :data="verificationRecords"
        border
        style="
          width: 100%;
          --el-table-border-color: #cdd7d5;
          --el-table-text-color: #171717;
          --el-table-header-text-color: #585858;
        "
        :header-cell-style="{
          background: '#e5f5f3', // 背景色
          color: '#585858' // 文字颜色
        }"
        :row-style="tableRowStyle"
      >
        <ElTableColumn prop="serialNo" label="序号" width="80" align="center" />
        <ElTableColumn prop="stage" label="环节名称" width="120" align="center" />
        <ElTableColumn prop="result" label="审核/审批结果" width="150" align="center">
          <template #default="scope">
            <span
              :class="{
                'text-success': scope.row.result === '通过',
                'text-danger': scope.row.result === '不通过'
              }"
            >
              {{ scope.row.result }}
            </span>
          </template>
        </ElTableColumn>
        <ElTableColumn prop="opinion" label="审核/审批意见" align="center" />
        <ElTableColumn prop="department" label="审核/审批部门" width="150" align="center" />
        <ElTableColumn prop="approver" label="审核/审批人员" width="120" align="center" />
        <ElTableColumn prop="approvalTime" label="审核/审批时间" width="180" align="center" />
      </ElTable>
    </div>

    <!-- 审核结果 -->
    <div class="verification-result mt-20">
      <ElRow>
        <ElCol :span="24">
          <div class="result-item">
            <span class="label">审核/审批结果：</span>
            <ElRadioGroup v-model="verificationResult">
              <ElRadio label="通过">通过</ElRadio>
              <ElRadio label="不通过">不通过</ElRadio>
            </ElRadioGroup>
          </div>
        </ElCol>
      </ElRow>

      <ElRow class="mt-10">
        <ElCol :span="24">
          <div class="result-item">
            <span class="label">审核/审批意见：</span>
            <ElInput
              v-model="verificationOpinion"
              type="textarea"
              :rows="4"
              placeholder="请输入审核/审批意见"
            />
          </div>
        </ElCol>
      </ElRow>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons mt-20">
      <ElButton type="primary" @click="submitVerification">保存</ElButton>
      <ElButton
        color="#286af6"
        style="--el-button-text-color: #fff; --el-button-hover-text-color: #fff"
        @click="viewFile"
      >
        档案核查</ElButton
      >
      <ElButton
        color="#ff6b35"
        style="--el-button-text-color: #fff; --el-button-hover-text-color: #fff"
        >档案归档</ElButton
      >
    </div>
  </div>

  <!-- 档案核查弹窗 -->
  <ElDialog
    v-model="fileVerificationDialogVisible"
    title="档案核查"
    width="500px"
    :show-close="!isLoading"
    :close-on-click-modal="!isLoading"
    :close-on-press-escape="!isLoading"
    destroy-on-close
    class="verification-dialog"
  >
    <div class="verification-dialog-content">
      <!-- 加载中状态 -->
      <div v-if="isLoading" class="loading-container">
        <div class="loading-icon">
          <Icon icon="vi-ep:loading" :size="100" class="is-loading" />
        </div>
        <div class="loading-text">
          <p>正在进行档案核查，请稍候...</p>
        </div>
      </div>

      <!-- 核查完成状态 -->
      <div v-else class="verification-result-container">
        <div class="result-icon">
          <Icon icon="vi-ep:warning" :size="100" class="warning-icon" />
        </div>
        <p class="result-title">请注意！</p>

        <div class="suggestion-section">
          <h4 class="suggestion-title">核查整改建议：</h4>
          <div class="suggestion-content" :class="{ 'error-content': aiAnalysisError }">
            {{ aiAnalysisError || verificationSuggestion }}
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="closeVerificationDialog" :disabled="isLoading">取 消</ElButton>
        <ElButton
          v-if="!isLoading && verificationSuggestion && !aiAnalysisError"
          type="primary"
          @click="applyVerificationSuggestion"
        >
          确 认
        </ElButton>
      </div>
    </template>
  </ElDialog>

  <!-- 侧边栏聊天组件 -->
  <ChatSidebarPanel
    ref="chatSidebarRef"
    :api-key="DIFY_API_KEY_changjing2"
    :api-base="DIFY_API_V1_URL"
    :inputs="aiInputs"
    title="在途工单核查"
    placeholder="请输入您想了解的问题..."
    welcome-message="您好！我是在途工单核查助手。我可以帮您分析在途工单核查问题，提供解决方案。请问有什么需要帮助的吗？"
    @message-end="handleAiFinish"
    @before-open="handleBeforeOpen"
    :show-float-button="true"
  />
</template>

<style lang="scss" scoped>
.el-table .even-row {
  --el-table-tr-bg-color: #ffffff !important;
}

.el-table .odd-row {
  --el-table-tr-bg-color: #f6f6f6 !important;
}

.verification-page {
  background-color: #fff;
  padding: 20px;
}

.page-title {
  color: #409eff;
  font-size: 18px;
  margin-bottom: 10px;
}

.section-title {
  // font-size: 16px;
  // font-weight: 600;
  // margin-bottom: 15px;
}

.info-section {
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.info-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;

  .label {
    min-width: 100px;
    color: #606266;
    font-weight: 500;
  }

  .value {
    flex: 1;
    word-break: break-all;
  }
}

.verification-section {
  margin-top: 20px;
}

.verification-result {
  margin-top: 20px;

  .result-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 15px;

    .label {
      min-width: 120px;
      color: #606266;
      font-weight: 500;
      margin-top: 8px;
    }

    :deep(.el-textarea) {
      width: 100%;
    }
  }
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 30px;
}

/* 档案核查弹窗样式 */
.verification-dialog {
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 30px 20px;
    text-align: center;

    .loading-icon {
      font-size: 200px !important;
      color: #e6a23c;
      margin-bottom: 20px;

      .is-loading {
        animation: rotating 2s linear infinite;
      }
    }

    .loading-text {
      p {
        margin: 5px 0;
        font-size: 16px;

        &:first-child {
          font-weight: bold;
          font-size: 18px;
        }
      }
    }
  }

  .verification-result-container {
    padding: 20px;
    text-align: center;

    .result-icon {
      font-size: 60px;
      color: #e6a23c;
      margin-bottom: 15px;
    }

    .result-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 20px;
    }

    .suggestion-section {
      text-align: left;
      margin-top: 15px;

      .suggestion-title {
        font-size: 16px;
        margin-bottom: 10px;
        color: #606266;
      }

      .suggestion-content {
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        padding: 12px 15px;
        background-color: #f5f7fa;
        font-size: 14px;
        line-height: 1.6;
        color: #303133;
        white-space: pre-line;
        min-height: 100px;
        max-height: 400px;
        overflow: auto;

        &.error-content {
          color: #f56c6c;
          background-color: #fef0f0;
          border-color: #fbc4c4;
        }
      }
    }
  }
}

.mt-10 {
  margin-top: 10px;
}

.mt-20 {
  margin-top: 20px;
}

.text-success {
  color: #67c23a;
}

.text-danger {
  color: #f56c6c;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>
